﻿//Copyright © Omega Point 2008
//All rights reserved.
//This Software is Licensed under the New BSD License
//for a full copy of this license see http://www.codeplex.com/networkmessenger/license
//Redistributions of source code must retain the above copyright notice.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace NetworkMessenger
{
    public partial class TrayForm : Form
    {
        
        public TrayForm()
        {
            InitializeComponent();

            if (Properties.Settings.Default.LastSentTo == null)
            {
                Tools.UpgradeSettings();  
            }

            srv = new MessageServer(Tools.GetPortFromName(Environment.UserName.ToLower()));
            srv.OnNewMessage += new MessageEventHandler(srv_OnNewMessage);

            chats = new Dictionary<Guid, ChatWindow>();
            try
            {
                srv.RunServer();
            }
            catch (Exception)
            {
                MessageBox.Show("Unable to Start, Check Network Messenger is not already running", "Network Messenger", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
                App.Current.Shutdown();
            }            
        }
       
        private Dictionary<Guid,ChatWindow> chats;
        private MessageServer srv;

        #region Message Received
        private void handleChat(object msg)
        {
            Message chatMessage = (Message)msg;
            if (chats.ContainsKey(chatMessage.ChatID))
            {
                chats[chatMessage.ChatID].ShowMessage(chatMessage);
            }
            else
	        {
                chats.Add(chatMessage.ChatID, new ChatWindow(chatMessage.ChatID, chatMessage.From));
                chats[chatMessage.ChatID].Closed += new EventHandler(window_Closed);
                chats[chatMessage.ChatID].ShowMessage(chatMessage);
                chats[chatMessage.ChatID].ShowDialog();                      
	        }
        }

        private void window_Closed(object sender, EventArgs e)
        {
            chats.Remove(((ChatWindow)sender).ChatID);
        }

        private static void ShowMessage(object msg)
        {
            ReceivedMessageWindow messageWindow = new ReceivedMessageWindow((Message)msg);            
            messageWindow.ShowDialog();
            messageWindow = null;
        }

        private void srv_OnNewMessage(object sender, MessageEventArgs e)
        {
            if (e.MessageReceived.IsChat)
            {
                Thread msgDispThread = new Thread(new ParameterizedThreadStart(handleChat));
                msgDispThread.SetApartmentState(ApartmentState.STA);
                msgDispThread.Start(e.MessageReceived);
            }
            else
            {
                Thread messageDisplayThread = new Thread(new ParameterizedThreadStart(ShowMessage));
                messageDisplayThread.SetApartmentState(ApartmentState.STA);
                messageDisplayThread.Start(e.MessageReceived);
                messageDisplayThread.Name = "DisplayMessageWindow";
            }
        }
        #endregion

        #region Context Events
        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
            App.Current.Shutdown();
        }
        private void sendMessageToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Thread sendThread = new Thread(new ThreadStart(ShowSendForm));
            sendThread.SetApartmentState(ApartmentState.STA);
            sendThread.Start();
        }
        private void ShowSendForm()
        {
            SendMessageWindow sendWindow = new SendMessageWindow();
            sendWindow.ShowDialog();
            sendWindow = null;
        }



        private void startChatToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Thread sendThread = new Thread(new ThreadStart(NewChat));
            sendThread.SetApartmentState(ApartmentState.STA);
            sendThread.Start();
        }
        #endregion

        #region Info Display
        private void ShowInfoForm()
        {
            InfoWindow info = new InfoWindow();
            info.ShowDialog();
            info = null;
        }

        private void informationToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Thread infoThread = new Thread(new ThreadStart(ShowInfoForm));
            infoThread.SetApartmentState(ApartmentState.STA);
            infoThread.Start();
        }
        #endregion

        private void NewChat()
        {
            StartChatWindow win = new StartChatWindow();
            if (win.ShowDialog() == true)
            {
                Guid newChatId = Guid.NewGuid();
                chats.Add(newChatId,new ChatWindow(newChatId, win.ChatWith));
                win = null;

                chats[newChatId].Closed += new EventHandler(window_Closed);
                chats[newChatId].ShowDialog();
            }
        }

        /// <summary>
        /// Refreshes the Tray Context Menu
        /// </summary>
        private void RefreshMenu()
        {
            if (srv.IsRunning)
            {
                startServerToolStripMenuItem.Text = "&Stop Server"; 
            }
            else
            {
                startServerToolStripMenuItem.Text = "&Start Server";
            }
        }

        private void trayContexMenu_Opening(object sender, CancelEventArgs e)
        {
            RefreshMenu();
        }

        private void startServerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (srv.IsRunning)
            {
                srv.StopServer();
            }
            else
            {
                srv.RunServer();
            }
        }
    }
}
